package com.heba.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;

/**
 * viewpager中使用
 * fragment延迟加载
 * Created by jason on 2020/6/22.
 */
public abstract class LazyFragment extends BaseFragment {

    /**
     * 当前fragment是否可见
     */
    public boolean isVisibleToUser = false;

    /**
     * 是否已创建view
     */
    private boolean isViewCreated = false;

    /**
     * 是否第一次加载数据
     */
    private boolean isFirstLoad = true;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        onLazyLoad();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreated = true;
        onLazyLoad();
    }

    /**
     * view对用户可见时执行
     */
    private void onLazyLoad() {
        if (isViewCreated && isVisibleToUser && isFirstLoad) {
            isFirstLoad = false;
            lazyLoad();
        }
    }

    protected abstract void lazyLoad();

}
